package com.prp.bo;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

import org.hibernate.Transaction;

import com.prp.algorithm.Division;
import com.prp.db.DAOFactory;
import com.prp.db.HibernateSessionFactory;
import com.prp.db.idao.ICommunityDAO;
import com.prp.db.idao.IUserInformationDAO;
import com.prp.db.po.Community;
import com.prp.db.po.UserInformation;
import com.prp.gwt.client.vo.CommunityList;
import com.prp.gwt.client.vo.UserList;

public class Administrator {

	private final static ReentrantLock lock = new ReentrantLock();

	/**
	 * @author arthur
	 * @param identity
	 *            用户的权限级别
	 * @return 特定权限的所有用户
	 */
	public static UserList getUserListByIdentity(int identity) {
		DAOFactory factory = DAOFactory.getDAOFactory();
		IUserInformationDAO userDAO = factory.getUserInformationDAO();
		List<UserInformation> list = userDAO.findByIdentity(identity);
		UserList userList = new UserList();
		for (UserInformation info : list)
			userList.addUser(com.prp.bo.User.parse(info));
		return userList;
	}

	/**
	 * @author arthur 读取community表,找出所有的社区id 读取user_information表,统计给定社区id的人数
	 *         建立Community对象,用社区id和社区人数进行赋值
	 * @author arthur
	 * @return 社区列表
	 */
	public static CommunityList getCommunityList() {
		DAOFactory factory = DAOFactory.getDAOFactory();
		IUserInformationDAO userDAO = factory.getUserInformationDAO();
		ICommunityDAO communityDAO = factory.getCommunityDAO();
		List<Community> l = communityDAO.findAll();
		CommunityList list = new CommunityList();
		for (Community c : l) {
			com.prp.gwt.client.vo.Community community = new com.prp.gwt.client.vo.Community();
			community.setId(c.getCommunityId());
			community.setNum(userDAO.getCommunitySize(c.getCommunityId()));
			list.addCommunity(community);
		}
		return list;
	}

	/**
	 * @author arthur
	 * @return 所有未激活用户的列表
	 */
	public static UserList getInactivatedUserList() {
		DAOFactory factory = DAOFactory.getDAOFactory();
		IUserInformationDAO userDAO = factory.getUserInformationDAO();
		List<UserInformation> list = userDAO.findByActivated(false);
		UserList userList = new UserList();
		for (UserInformation info : list)
			userList.addUser(User.parse(info));
		return userList;
	}

	/**
	 * @author arthur 如果id为-1,表示查找尚未划分社区的所有用户
	 *         查找用户之前,将hibernate的session清楚,否则可能无法得到最新的数据
	 *         如果用户为该社区的核心成员,将该用户的isCore属性设置为true,默认为false
	 * 
	 * @param communityId
	 *            社区id
	 * @return 社区id为communityId的所有用户列表
	 */
	public static UserList getUserListByCommunity(int communityId) {
		DAOFactory factory = DAOFactory.getDAOFactory();
		ICommunityDAO communityDAO = factory.getCommunityDAO();
		IUserInformationDAO userDAO = factory.getUserInformationDAO();
		if (communityId == -1) {
			List<UserInformation> infoList = userDAO.findByCommunityId(null);
			UserList userList = new UserList();
			for (UserInformation info : infoList)
				userList.addUser(User.parse(info));
			return userList;
		} else {
			if(communityDAO.findById(communityId) == null)
				return null;
			HibernateSessionFactory.getSession().clear();
			String s = communityDAO.findById(communityId).getCommunityName();
			String[] ids = s.split("-");
			int id1 = Integer.valueOf(ids[0]);
			int id2 = Integer.valueOf(ids[1]);
			List<UserInformation> infoList = userDAO
					.findByCommunityId(communityId);
			UserList userList = new UserList();
			for (UserInformation info : infoList) {
				com.prp.gwt.client.vo.User user = User.parse(info);
				if (info.getUserId() == id1 || info.getUserId() == id2)
					user.setCore(true);
				userList.addUser(user);
			}
			return userList;
		}
	}

	/**
	 * @author arthur 将指定用户的权限设为指定权限 info不能为null
	 * @param info
	 *            指定用户
	 * @param identity
	 *            权限
	 */
	public static void setIdentity(UserInformation info, int identity) {
		DAOFactory factory = DAOFactory.getDAOFactory();
		IUserInformationDAO userDAO = factory.getUserInformationDAO();
		Transaction tx = null;
		try {
			tx = HibernateSessionFactory.getSession().beginTransaction();
			info.setIdentity(identity);
			userDAO.attachDirty(info);
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			HibernateSessionFactory.getSession().close();
		}
	}

	/**
	 * @author arthur 调用社区划分 这是一个非阻塞调用 尝试获得一把锁 如果锁已经被锁上,说明算法已经开始运行,则立即返回
	 *         获得锁后,服务器开启一个新的线程进行社区划分
	 */
	public static void divideCommunity() {
		Runnable r = new Runnable() {

			@Override
			public void run() {
				if (lock.tryLock()) {
					try {
						Division.divide();
					} finally {
						lock.unlock();
					}
				}
			}
		};
		new Thread(r).start();
	}

	/**
	 * @author arthur
	 * @return 社区划分算法是否正在运行
	 */
	public static boolean isDivideRunning() {
		return !lock.isLocked();
	}

	/**
	 * @author arthur
	 * @param query
	 *            用户输入部分email关键字
	 * @return 返回提示词,提示词的数量不超过10个
	 */
	public static List<String> getEmailSuggest(String query) {
		DAOFactory factory = DAOFactory.getDAOFactory();
		IUserInformationDAO userDAO = factory.getUserInformationDAO();
		List<String> list = userDAO.findStringByEmailPattern(query + "%");
		if (list.size() < 10)
			return list;
		List<String> newList = new ArrayList<String>();
		for (int i = 0; i < 10; i++)
			newList.add(list.get(i));
		return newList;
	}

	/**
	 * @author arthur
	 * @param query
	 *            用户输入部分name关键字
	 * @return 返回提示词,提示词的数量不超过10个
	 */
	public static List<String> getNameSuggest(String query) {
		DAOFactory factory = DAOFactory.getDAOFactory();
		IUserInformationDAO userDAO = factory.getUserInformationDAO();
		List<String> list = userDAO.findStringByNamePattern(query + "%");
		if (list.size() < 10)
			return list;
		List<String> newList = new ArrayList<String>();
		for (int i = 0; i < 10; i++)
			newList.add(list.get(i));
		return newList;
	}

	/**
	 * @author arthur
	 * @param email
	 *            需要激活的用户email
	 * @return 激活成功返回true,否则返回false
	 */
	public static boolean activateUser(String email) {
		DAOFactory factory = DAOFactory.getDAOFactory();
		IUserInformationDAO userDAO = factory.getUserInformationDAO();
		Transaction tx = null;
		try {
			tx = HibernateSessionFactory.getSession().beginTransaction();
			UserInformation user = (UserInformation) userDAO.findByEmail(email)
					.get(0);
			if (user == null)
				return false;
			user.setActivated(true);
			userDAO.attachDirty(user);
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			HibernateSessionFactory.getSession().close();
		}
		return true;
	}

	/**
	 * @author arthur 如果找补到指定用户,删除失败
	 * @param email
	 *            指定用户的email
	 * @return 删除成功返回true,否则返回false
	 */
	public static boolean deleteUser(String email) {
		DAOFactory factory = DAOFactory.getDAOFactory();
		IUserInformationDAO userDAO = factory.getUserInformationDAO();
		Transaction tx = null;
		try {
			tx = HibernateSessionFactory.getSession().beginTransaction();
			List<UserInformation> list = userDAO.findByEmail(email);
			if (list == null || list.size() == 0)
				return false;
			userDAO.delete(list.get(0));
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			HibernateSessionFactory.getSession().close();
		}
		return true;
	}

	/**
	 * @author arthur
	 * @param name
	 *            需要查找的用户姓名
	 * @return 满足匹配的所有用户姓名
	 */
	public static UserList searchByName(String name) {
		DAOFactory factory = DAOFactory.getDAOFactory();
		IUserInformationDAO userDAO = factory.getUserInformationDAO();
		List<UserInformation> list = userDAO
				.findByNamePattern("%" + name + "%");
		UserList userList = new UserList();
		for (int i = 0; i < list.size(); i++)
			userList.addUser(User.parse(list.get(i)));
		return userList;
	}

}
